<template>
	<view class="page">
		<!-- 基本信息 -->
		<view class="hight20"></view>
		<view class="content">
			<view class="h3">
				完善基本信息
				<text class="red">（请确保信息准确无误）</text>
			</view>
			<view class="flexBox" style="padding-bottom: 0;">
				<!-- 身份证信息 -->
				<view class="placeholder">
					<view v-if="idCardImgFront == ''" @click="chooseImage('idCardImgFront')" class="uploadFile">
						<image mode="scaleToFill" src="/static/images/upload/sfzQ.png"  lazy-load="true"/>
						<view class="xjImg">
							<view class="xj"></view>
							<view class="btnCont">拍摄身份证正面</view>
						</view>
					</view>
					<view v-else class="uploadFile">
						<image mode="scaleToFill" @click="previewImage('idCardImgFront')" :src="baseImg+idCardImgFront"/>
						<view class="removeImg" @click="imgRemove('idCardImgFront')"></view>
					</view>
				</view>
				<view class="placeholder">
					<view v-if="idCardImgSide == ''" @click="chooseImage('idCardImgSide')" class="uploadFile">
						<image mode="scaleToFill" src="/static/images/upload/sfzQ.png"  lazy-load="true"/>
						<view class="xjImg">
							<view class="xj"></view>
							<view class="btnCont">拍摄身份证反面</view>
						</view>
					</view>
					<view v-else class="uploadFile">
						<image mode="scaleToFill" @click="previewImage('idCardImgSide')" :src="baseImg+idCardImgSide"/>
						<view class="removeImg" @click="imgRemove('idCardImgSide')"></view>
					</view>
				</view>
			</view>
			<view>
				<view class="list">
					<view class="form-row">
						<view class="form-row-label">姓　　名</view>
						<view class="form-row-content">
							<input @input="inputChange" id="userName" class="item-input" type="text" placeholder-class="phcolor" placeholder="请输入姓名" :value="userName">
						</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">身份证号</view>
						<view class="form-row-content">
							<input @input="inputChange" class="item-input" type="idcard" id="idCard" placeholder-class="phcolor" placeholder="请输入身份证" :value="idCard"/>
						</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">生　　日</view>
						<view class="form-row-content">
							<input 
								@input="inputChange"
								id="birthday" 
								placeholder-class="phcolor" 
								class="item-input" 
								type="text" 
								placeholder="请输入生日" 
								:value="birthday"/>
						</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">性　　别</view>
						<view class="form-row-content">
							<input @input="inputChange" id="sex" class="item-input" type="text" placeholder-class="phcolor" placeholder="请输入性别" :value="sex">
						</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">有效期止期</view>
						<view class="form-row-content">
							<input 
								@input="inputChange" 
								id="validity" 
								placeholder-class="phcolor" 
								class="input" 
								type="text" 
								placeholder="请输入证件有效期" 
								:value="expiryDate"/>
						</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">户籍地址</view>
						<view class="form-row-content">
							<input @input="inputChange" id="address" class="item-input" type="text" placeholder-class="phcolor" placeholder="请输入户籍地址" :value="address">
						</view>
					</view>
					<view class="form-row form-row-textarea">
						<view class="form-row-label">居住地址</view>
						<view class="form-row-content">
							<view>
								<view v-if="!liveValue" style="overflow: hidden;color: #959595;" id="live" @click="openSelect" class="item-input">请选择省份、城市、区县</view>
								<view v-else id="live" @click="openSelect" style="overflow: hidden;color: #191919;" class="item-input">{{liveValue}}</view>
								<ehPicker @conceal="conceal" v-if="popup" title="请选择省份、城市、区县" />
								<input @input="inputChange" id="residentialAddress3" class="item-input" type="text" placeholder-class="phcolor" placeholder="街道/小区/镇/乡/单位/门牌号" enableNative="false"/>
							</view>
						</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">本地居住年限</view>
						<view class="form-row-content">
							<input 
								@input="inputChange" 
								id="LiveTime" 
								placeholder-class="phcolor" 
								class="item-input" type="number" 
								maxlength="2" 
								placeholder="请输入现居住地年限" 
								:value="LiveTime"/>
						</view>
						<view class="unit">年</view>
					</view>
					<view class="form-row">
						<view class="form-row-label">年收入（元）</view>
						<view class="form-row-content">
							<input 
								@input="inputChange" 
								id="income" 
								placeholder-class="phcolor" 
								class="item-input" 
								type="digit" 
								placeholder="请输入年收入（元）" 
								:value="income"/>
						</view>
					</view>
					<view class="hight20"></view>
					<view class="" style="background-image:url(/static/images/xiajiantou.svg);">
						<picker @change="maritalListChange" :value="maritalIndex" :range="maritalList" range-key="value">
							<view class="row">
								<view class="row-title">婚姻状况</view>
								<view class="row-extra">{{maritalList[maritalIndex].value}}</view>
							</view>
						</picker>
					</view>
				</view>
			</view>
		</view>
		<view v-if="popup" class="fixedBox" @click="isFixedBox"></view>
		<view class="btnBox">
			<button size="default" class="btn" type="primary" :disabled="isDisabled" @click="nextBtn">提交申请</button>
		</view>
	</view>
</template>

<script>
	import {realNameAuthentication} from '@/service/message'
	import {createUser} from '@/service/chengyongche'
	import {imageDelete} from '@/service/uploadFile'
	import ehPicker from '../erha-picker/erha-picker.vue'; 

	import {
	  baseURL,
	  imgUrl
	} from '@/service/config'

	export default {
		components:{
			ehPicker
		},
		data() {
			return {
				popup: false,
				isDisabled: false,
				imgUrl: imgUrl,
				baseImg: imgUrl,
				baseURL: baseURL,
				qyIndex: 1,
				orderDetail: 0,
				userName: '',
				idCard: '',
				sex: '',
				validity: '',
				issueDate: '',
				expiryDate: '',
				cardNo: '',
				marital: '',  // 婚姻状况
				maritalIndex: 0,
				maritalImg: false,
				maritalList: [
					{id: 0, value: '请选择婚姻状况'},
					{id: 10, value: '未婚'},
					{id: 20, value: '已婚'},
					{id: 30, value: '丧偶'},
					{id: 40, value: '离婚'}
				],
				idCardImgFront: '',   // 身份证正面
				idCardImgSide: '',   // 身份证反面
				upList: [0, 0, 0],
				address: '',   // 户籍地址
				residentialAddress: '',   // 居住地址
				residentialAddress1: '',
				residentialAddress2: '',
				residentialAddress3: '',
				isBtn: false,
				liveValue: false, // 居住地址选择的值
				header: {},
				userInfo: {},
				orderId: '',
				birthday: '',
				LiveTime: '',
				income: '',
			}
		},
		onLoad(e) {
			const _this = this;
			let orderId = e.orderId;
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					_this.userInfo = res.data;
					_this.orderId = orderId;
					_this.header = {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': res.data.token
					};
				}
			});
		},
		onShow() {
			this.isBtn = false;
		},
		methods: {
			isFixedBox() {
				this.popup = false;
			},
			inputChange(e) {
				let typeName = e.currentTarget.id;
				this[typeName] = e.detail.value;
			},
			openSelect() {
				this.popup = true;
			},
			/**
			 * 关闭居住地址级联组件
			 * @method liveShow
			 */
			closeLive() {
				this.liveShow = false;
			},
			/**
			 * 居住地址点击确认触发的事件
			 * @method onLiveSuccess
			 * @param {*} result
			 */
			conceal(param) {
				// 获取到传过来的 省 市 区 县数据
				let province = param.province;
				let city = param.city;
				if(param.city == '市辖区') {
					city = '';
				}
				let area = param.area;
				this.liveValue = province + ' ' +  city + ' ' + area;
				
				this.residentialAddress = province;
				this.residentialAddressCode = param.provinceCode;
				city == ''? this.residentialAddress1 = province : this.residentialAddress1 = city;
				this.residentialAddress2 = area;

				// 选择完毕后隐藏
				this.popup = false;
			},
			maritalListChange(e) {
				const maritalList = this.maritalList;
				const thisIndex = e.detail.value;
				const marital = maritalList[thisIndex].id;
				this.marital = marital;
				this.maritalIndex = thisIndex;
			},
			chooseImage(type) {
				let _this = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					success: function (res) {
						let path = res.tempFilePaths
						let userInfoData = _this.userInfo;
						let header = {
							'Authorization': userInfoData.token
						};
						_this.uploadFile(type, _this, path, header, userInfoData);
					}
				});
			},
			// 删除图片
			imgRemove(removeName) {
				uni.showModal({
					content: '您确定要删除当前图片吗？',
					success: (e) => {
						if(e.confirm) {
							// 调用删除图片接口
							let userInfoData = this.userInfo;
							const newFilename = this[removeName];
							const filename = newFilename.substring(newFilename.lastIndexOf("/")+1);
							const prams = '{"filename":"'+filename+'","userId":"'+userInfoData.userId+'"}';
							let header = {
								'Authorization': userInfoData.token
							};
							this._imageDelete(prams, removeName, header);
						}
					}
				});
			},
			// 预览图片
			previewImage(type) {
				let viewImgs = [];
				let _this = this;
				viewImgs.push(imgUrl + this[type])
				uni.previewImage({ urls: viewImgs });
			},
			/**
			 * 点击确定按钮触发
			 * @method nextBtn
			 */
			nextBtn() {
				const _this = this;
				const regu = /^[0-9]+(\.\d{1,2})?$/;
				_this. isBtn = true;
				if (_this.idCardImgFront == "") {
					uni.showToast({
						icon: 'none',
						title: '请上传身份证正面',
						duration: 3000
					});
					_this. isBtn = false;
				} else if (_this.idCardImgSide == '') {
					uni.showToast({
						icon: 'none',
						title: '请上传身份证反面',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.userName == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入姓名',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.idCard == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入身份证号',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.birthday == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入生日',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.sex == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入性别',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.address == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入户籍地址',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.liveValue == '') {
					uni.showToast({
						icon: 'none',
						title: '请选择居住地址省份、城市、区县',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.residentialAddress3 == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入居住地址区/县/街道/小区/镇/乡/单位/门牌号',
						duration: 3000
					});
					_this.focus3 = true;
					_this.isBtn = false;
				} else if (_this.LiveTime == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入本地居住年限',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.income == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入年收入',
						duration: 3000
					});
					_this.isBtn = false;
				} else if(_this.income < 30000) {
					uni.showToast({
						icon: 'none',
						title: '年收入不能低于3万',
						duration: 3000
					});
					_this.isBtn = false;
				} else if (_this.marital == '' || _this.marital == '0') {
					uni.showToast({
						icon: 'none',
						title: '请选择婚姻状况',
						duration: 3000
					});
					_this.isBtn = false;
				} else {
					
					const prams = {userName: _this.userName, idCard: _this.idCard};
					_this._realNameAuthentication(prams, this.header);
				}
			},
			getBirthdayFromIdCard(idCard) {  
				let birthday = "";  
				if(idCard != null && idCard != ""){  
					if(idCard.length == 15){  
							birthday = "19"+idCard.substr(6,6);  
					} else if(idCard.length == 18){  
							birthday = idCard.substr(6,8);  
					}  
					birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");  
				}  
				return birthday;  
			}, 
			getAgeFromIdCard(UUserCard) {
				//获取年龄
				var myDate = new Date();
				var month = myDate.getMonth() + 1;
				var day = myDate.getDate();
				var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
				if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
					age++;
				}
				return age;
			},
			insertStr(soure, start, newStr){   
				return soure.slice(0, start) + newStr + soure.slice(start);
			},
			// -----------------------网络请求--------------------------
			uploadFile(type, that, path, header, userInfoData) {
				let urls = baseURL+'/file/imageUploads';
				if(type == 'idCardImgFront' || type == 'idCardImgSide') {
					urls = baseURL+'/file/idCardImgUploads';
				}
				uni.uploadFile({
					url: urls,
					filePath: path[0],
					fileType: 'image',
					name: 'file',
					header: header,
					formData: {
						"userId": userInfoData.mobile,
						"orderId": this.orderId
					},
					success: (res) => {
						const resultData = JSON.parse(res.data);
						if(resultData.resultCode != "0000") {
							uni.showModal({
								content: resultData.resultMsg,
								showCancel: false,
								success: () => {
									uni.hideLoading();
								}
							});
						}else {
							const url = resultData.data.url;
							that[type] = url;
							if(type == 'idCardImgFront') {
								if(resultData.data.userName == '' || resultData.data.userName == undefined || resultData.data.userName == null) {
									uni.showModal({
										content: '请上重新上传身份证正面',
										showCancel: false,
										success: () => {
											// 调用删除图片接口
											const newFilename = that[type];
											const filename = newFilename.substring(newFilename.lastIndexOf("/")+1);
											const prams = '{"filename":"'+filename+'","userId":"'+userInfoData.userId+'"}';
											const removeName = type;
											let header = {
												'content-type': 'multiprat/form-data',
												'Authorization': userInfoData.token
											};
											that._imageDelete(prams, removeName, header);
										}
									});
								}else {
									that.idCardImgFront = resultData.data.url;
									that.userName = resultData.data.userName;
									that.idCard = resultData.data.idCard;
									that.birthday = that.getBirthdayFromIdCard(resultData.data.idCard);
									that.age = that.getAgeFromIdCard(resultData.data.idCard);
									that.sex = resultData.data.sex;
									that.sexCode = resultData.data.sex=="男" ? 1 : 2;
									that.address = resultData.data.address;
								}
							}
							if(type == 'idCardImgSide') {
								if(!resultData.data.issueDate && !resultData.data.expiryDate) {
									uni.showModal({
										content: '请上重新上传身份证反面',
										showCancel: false,
										success: () => {
											// 调用删除图片接口
											const newFilename = that[type];
											const filename = newFilename.substring(newFilename.lastIndexOf("/")+1);
											const prams = '{"filename":"'+filename+'","userId":"'+userInfoData.userId+'"}';
											const removeName = type;
											let header = {
												'content-type': 'multiprat/form-data',
												'Authorization': userInfoData.token
											};
											that._imageDelete(prams, removeName, header);
										}
									});
								}else {
									const idCardImgSide = resultData.data.url;
									let issueDate = resultData.data.issueDate;
									let validity = '';
									issueDate = that.insertStr(issueDate, 4, "-");
									issueDate = that.insertStr(issueDate, 7, "-");
									let expiryDate = resultData.data.expiryDate;
									if(expiryDate != "长期") {
										expiryDate = that.insertStr(expiryDate, 4, "-");
										expiryDate = that.insertStr(expiryDate, 7, "-");
										validity = expiryDate;
									}else {
										validity = '9999-12-31';
									}
									that.idCardImgSide = idCardImgSide
									that.issueDate = issueDate
									that.expiryDate = expiryDate
									that.validity = validity
								}
							}
						}
					}
				});
			},
			_imageDelete(prams, removeName, header) {
				imageDelete(prams, header).then(res => {
					const data = res.data;
					if(data.resultCode != "0000") {
						uni.showModal({
							icon: 'none',
							title: res.data.resultMsg,
							success: () => {
								uni.hideLoading();
							}
						});
					}else {
						this[removeName] = '';
					}
				}).catch(err => {
					nui.hideLoading();
				})
			},
			_realNameAuthentication(prams, header) {
				const _this = this;
				uni.showLoading();
				_this.isBtn = false;
				uni.setStorage({
					key: 'idCardInfo',
					data: {
						name: _this.userName,
						idCard: _this.idCard
					},
					success: function(res) {
						const user_name = _this.userName;
						const cert_no = _this.idCard;
						const age = _this.age;
						const indiv_sex = _this.sexCode;
						const birthday = _this.birthday;
						const cert_valid = _this.validity;
						const address = _this.address;
						const id_card_img_front = _this.idCardImgFront;
						const id_card_img_side = _this.idCardImgSide;
						const live_province = _this.residentialAddress;
						const provCode = _this.residentialAddressCode;
						const live_city = _this.residentialAddress1;
						const live_area = _this.residentialAddress2;
						const live_addr = _this.residentialAddress3;
						const local_years = _this.LiveTime;
						const annual_income = _this.income;
						const marital = _this.marital;
						const orderId = _this.orderId;
						const mobile = _this.userInfo.mobile;
						const siteUserId = mobile;
						const prams = {
							orderId,
							siteUserId,
							user_name,
							mobile,
							cert_no,
							age,
							indiv_sex,
							birthday,
							mobile,
							cert_valid,
							address,
							id_card_img_front,
							id_card_img_side,
							live_province,
							provCode,
							live_city,
							live_area,
							live_addr,
							local_years,
							annual_income,
							marital
						}
						_this._createUser(prams, _this.header);
					}
				})
				/* realNameAuthentication(JSON.stringify(prams), header).then(res => {
					if (res.data.resultCode != "0000") {
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: res.data.resultMsg,
							complete: () => {
								uni.hideLoading();
								_this.isBtn = false;
							}
						});
					} else {
						if (res.data.data.status == "success") {
							uni.hideLoading();
							_this.isBtn = false;
							uni.setStorage({
								key: 'idCardInfo',
								data: {
									name: _this.userName,
									idCard: _this.idCard
								},
								success: function(res) {
									const user_name = _this.userName;
									const cert_no = _this.idCard;
									const age = _this.age;
									const indiv_sex = _this.sexCode;
									const birthday = _this.birthday;
									const cert_valid = _this.validity;
									const address = _this.address;
									const id_card_img_front = _this.idCardImgFront;
									const id_card_img_side = _this.idCardImgSide;
									const live_province = _this.residentialAddress;
									const provCode = _this.residentialAddressCode;
									const live_city = _this.residentialAddress1;
									const live_area = _this.residentialAddress2;
									const live_addr = _this.residentialAddress3;
									const local_years = _this.LiveTime;
									const annual_income = _this.income;
									const marital = _this.marital;
									const orderId = _this.orderId;
									const mobile = _this.userInfo.mobile;
									const siteUserId = mobile;
									const prams = {
										orderId,
										siteUserId,
										user_name,
										mobile,
										cert_no,
										age,
										indiv_sex,
										birthday,
										mobile,
										cert_valid,
										address,
										id_card_img_front,
										id_card_img_side,
										live_province,
										provCode,
										live_city,
										live_area,
										live_addr,
										local_years,
										annual_income,
										marital
									}
									_this._createUser(prams, _this.header);
								}
							})
						} else {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: res.data.data.desc,
								duration: 3000
							});
							_this.isBtn = false;
						}
					}
				}).catch(err => {
					_this.isBtn = false;
					uni.hideLoading();
				}) */
			},
			_createUser(prams, header) {
				uni.showLoading();
				let _this = this;
				createUser(JSON.stringify(prams), header).then(res => {
					uni.hideLoading();
					if(res.data.resultCode != "0000") {
						uni.showModal({
							showCancel: false,
							title: res.data.resultMsg,
							complete: () => {
								uni.hideLoading();
								_this.isBtn = false;
							}
						});
					}else {
						uni.showModal({
							showCancel: false,
							title: '您好，您的审核资料已提交完成，审核结果会稍后反馈给您。',
							complete: () => {
								uni.reLaunch({ url: '/pages/profile/profile' })
							}
						});
					}
				}).catch(err => {
					_this.isBtn = false;
					uni.hideLoading();
				})
			},
		}
	}
</script>

<style>
	@import url("/pages/initial/personal-information/personal-information.css");
	.page {
		background: #eaeaea;
	}
	.unit {
		padding-left: 20rpx;
	}
</style>
